package com.hongye.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.hongye.app.model.GoodsModel;
import com.hongye.app.model.OrderGoodsModel;
import com.hongye.app.model.OrderInfoModel;
import com.hongye.app.model.UserAppModel;
import com.hongye.util.Utils;
import com.jfinal.core.Controller;

public class OrderController extends Controller{
	
//	private static final String DocPath = "http://120.27.117.192/rbg/doc/";//下载路径
	private static final String DocPath = "C:/MyPro/apache-tomcat-7.0.70/webapps/rbg/doc/";//下载路径
	public OrderController() {
		
	}

	/**
	 * 获取订单列表
	 * @author liushaomin
	 * 2016年10月6日
	 */
	public void orderview(){
//		List<OrderInfoModel> lst = OrderInfoModel.dao.ordersReview(this.getParaToInt("pageNumber",1)).getList();
		List<OrderInfoModel> lst = OrderInfoModel.dao.getAllOrder();
		String[] ids = new String[lst.size()];
		for (int i = 0; i < ids.length; i++) {
			int id = lst.get(i).get("id");
			ids[i] = String.valueOf(id);
		}
		this.setAttr("orderview", lst);
		this.setAttr("ids", Arrays.toString(ids));
		this.renderJsp("order.jsp");
	}
	
	/**
	 * 查看订单详情
	 * @author liushaomin
	 * 2016年10月8日
	 */
	public void orderDetail(){
		String id = this.getPara("id");
		String sql = "select * from order_info where id = "+ id +"";
		OrderInfoModel order = OrderInfoModel.dao.findFirst(sql);
		String sql_ordergoods = "select * from order_goods where order_id = "+ order.get("id") +"";
		List<OrderGoodsModel> ordergoods = OrderGoodsModel.dao.find(sql_ordergoods);
		UserAppModel buyer = UserAppModel.getByPhone(order.getStr("phone"));
		String sql_seller = "select * from buyer b, buyer_statistics bs where bs.buyer_id = b.user_id and b.user_id = '"+ ordergoods.get(0).getInt("seller_id")+"'";
		UserAppModel seller = UserAppModel.dao.findFirst(sql_seller);
		order.put("buyer_nick", buyer.getStr("nick"));
		order.put("seller_nick", seller.getStr("nick"));
		order.put("seller_phone", seller.getStr("phone"));
		order.put("seller_shopname", seller.getStr("shop_name"));
		this.setAttr("order", order);
		this.setAttr("ordergoods", ordergoods);
		this.renderJsp("orderDetail.jsp");
	}
	
	/**
	 * 筛选订单列表
	 * @author lifuqiang
	 * 2016-12-22
	 */
	public void screen(){
		String startTime = this.getPara("startTime");
		String endTime = this.getPara("endTime");
		String state = this.getPara("state");
		String time_start = null;
		String time_end = null;
		if(startTime.equals("")){
			startTime = "01/01/2017";
		}
		if(endTime.equals("")){
			time_end = Utils.getDate().toString();
		}else{
			time_end = Utils.sdfTosdf(endTime, "MM/dd/yyyy", "yyyy-MM-dd HH:mm:ss");
		}
		if(state == null){
			state = "0,1,2,3,4,5,6,7,8,9,10,11";
		}
		time_start = Utils.sdfTosdf(startTime, "MM/dd/yyyy", "yyyy-MM-dd HH:mm:ss");
		List<OrderInfoModel> orderinfo_list  = OrderInfoModel.getOrder_Admin(time_start, time_end, state);
		String[] ids = new String[orderinfo_list.size()];
		for (int i = 0; i < ids.length; i++) {
			int id = orderinfo_list.get(i).get("id");
			ids[i] = String.valueOf(id);
		}
		this.setAttr("orderview", orderinfo_list);
		this.setAttr("ids", Arrays.toString(ids));
		this.renderJsp("order.jsp");
		
	}
	
	/**
	 * 调用下载
	 * @author lifuqiang
	 * 2016-12-21
	 * @throws Exception 
	 */
	public void download(){
		String idstr = this.getPara("ids");
		String[] ids = idstr.substring(1, idstr.length()-1).split(", ");
		try {
			exportexcel(ids,this.getResponse());
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.renderNull();
	}
	
	/**
	 * 下载交易信息到Excel
	 * @author lifuqiang
	 * 2016-12-21
	 */
	@SuppressWarnings("resource")
	public void exportexcel(String[] ids, HttpServletResponse response) throws Exception{
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("订单统计表.xls");//创建一个工作表aa.xls
		sheet.setColumnWidth(0, 3000);//设置列宽
		sheet.setColumnWidth(1, 8000);
		sheet.setColumnWidth(2, 12000);
		sheet.setColumnWidth(3, 3000);
		sheet.setColumnWidth(4, 3000);
		sheet.setColumnWidth(5, 3000);
		sheet.setColumnWidth(6, 5000);
		sheet.setColumnWidth(7, 5000);
		sheet.setColumnWidth(8, 5000);
		sheet.setColumnWidth(9, 5000);
		HSSFCellStyle style = wb.createCellStyle();//获取单元格样式对象
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置居中
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		
        HSSFRow row = sheet.createRow((int) 0); // 开始填充数据
		HSSFCell cellScore = null;
		String state = null ;
		short colNum = 0;// 列起始
		cellScore = row.createCell(0);   //设置表头
		cellScore.setCellValue("序号");  
		cellScore.setCellStyle(style);  
		cellScore = row.createCell(1);  
		cellScore.setCellValue("订单编号");  
		cellScore.setCellStyle(style);  
        cellScore = row.createCell(2);  
        cellScore.setCellValue("总价（元）");  
        cellScore.setCellStyle(style);  
        cellScore = row.createCell(3);  
        cellScore.setCellValue("地址");  
        cellScore.setCellStyle(style);  
        cellScore = row.createCell(4);  
        cellScore.setCellValue("创建时间");  
        cellScore.setCellStyle(style);  
        cellScore = row.createCell(5);  
        cellScore.setCellValue("更新时间");  
        cellScore.setCellStyle(style);  
		cellScore = row.createCell(6);  
        cellScore.setCellValue("支付状态");
        cellScore.setCellStyle(style);
		List<OrderInfoModel> list = new ArrayList<OrderInfoModel>();
		for (int i = 0; i < ids.length; i++) {
			list.add(OrderInfoModel.getOrderById(ids[i]));
		}
		for (int i = 0; i < list.size(); i++) {
			int nclo = colNum;
			row = sheet.createRow(i + 1);
			HSSFCell cell = row.createCell(0);
			cell.setCellValue(i+1);
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellScore.setCellValue(i);
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellScore.setCellValue(list.get(i).getStr("order_sn"));
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			float total_price= list.get(i).get("total_price");
			cellScore.setCellValue(String.valueOf(total_price));
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellScore.setCellValue(list.get(i).getStr("address"));
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			cellScore.setCellValue(Utils.sdfToDate(list.get(i).get("c_time").toString(), sdf));
			HSSFCellStyle cellStyle = wb.createCellStyle();
            HSSFDataFormat format= wb.createDataFormat();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置居中
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            cellStyle.setDataFormat(format.getFormat("yyyy/MM/dd HH:mm:ss"));
            cellScore.setCellStyle(cellStyle);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			Timestamp update_time = list.get(i).get("update_time");
			if(update_time==null){
				cellScore.setCellValue("");
			}else{
				cellScore.setCellValue(Utils.sdfToDate(list.get(i).get("update_time").toString(), sdf));
			}
			HSSFCellStyle cellStyle2 = wb.createCellStyle();
            HSSFDataFormat format2= wb.createDataFormat();
            cellStyle2.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置居中
            cellStyle2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            cellStyle2.setDataFormat(format2.getFormat("yyyy/MM/dd HH:mm:ss"));
            cellScore.setCellStyle(cellStyle2);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			if(0==list.get(i).getInt("order_status")){
				state = "待付款";
			}else if(1==list.get(i).getInt("order_status")){
				state = "付款确认中";
			}else if(2==list.get(i).getInt("order_status")){
				state = "待发货";
			}else if(3==list.get(i).getInt("order_status")){
				state = "已发货";
			}else if(4==list.get(i).getInt("order_status")){
				state = "已收到货物";
			}else if(5==list.get(i).getInt("order_status")){
				state = "待评论";
			}else if(6==list.get(i).getInt("order_status")){
				state = "订单已取消";
			}else if(7==list.get(i).getInt("order_status")){
				state = "交易完成 ";
			}else if(8==list.get(i).getInt("order_status")){
				state = "退款中";
			}else if(9==list.get(i).getInt("order_status")){
				state = "退款成功";
			}else if(10==list.get(i).getInt("order_status")){
				state = "退货中";
			}else if(11==list.get(i).getInt("order_status")){
				state = "退货成功";
			}
			cellScore.setCellValue(state);
			cellScore.setCellStyle(style);
		}
		
		String fileName = "订单统计信息表.xls";
		String myExcel = DocPath;
		String filePath = myExcel + fileName;
		FileOutputStream out = new FileOutputStream(filePath);// 创建xls文件
		wb.write(out);
		out.close();
		File file = new File(filePath);
		Utils.download(response, file, fileName);
	}
	
	/**
	 * 热播狗自营订单管理
	 * @author liushaomin
	 * 2017年8月17日
	 */
	public void rbgorderReview(){
		String sql = "select *,id as goodsid from goods WHERE seller_id = 61 order by c_time DESC";
		List<GoodsModel> lst = GoodsModel.dao.find(sql);
		this.setAttr("goodsReview",lst);
		this.renderJsp("rbgGoodsReview.jsp");
	}
	
}
